/**
 *
 */
package com.gbb.common.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.util.List;

/**
 * 通用工具类
 *
 * @author gaobingbing
 */
public class CommonUtils {

    /** 上次点击的时间 **/
    private static long lastClickTime;

    /**
     * 防暴力点击
     *
     * @return ture:多次点击，不处理
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;

        if(0 < timeD && timeD < 500) {
            lastClickTime = time;
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * <pre>
     * 控制EditText输入小数点之后的位数
     * editText.setFilters(new InputFilter[] { MilesUtils.getInputFilter(2,8) });
     * </pre>
     *
     * @param digLength 小数点之后保留位数
     * @param intLength 小数点之前保留位数
     */
    public static InputFilter getInputFilter(final int digLength,final int intLength) {
        // 设置小数位数控制
        InputFilter lengthfilter = new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source,int start,int end,Spanned dest,int dstart,int dend) {
                // 删除等特殊字符，直接返回
                if("".equals(source.toString())) {
                    return null;
                } else {
                    String dValue = dest.toString();
                    if(dValue.contains(".")) {// 有小数点
                        int dotIndex = dValue.indexOf(".");

                        // 输入的数字在小数点前面
                        if(dstart <= dotIndex) {
                            if(dValue.substring(0,dotIndex).length() > intLength - 1) {
                                return source.subSequence(0,0);
                            }
                            return null;
                        } else {
                            String[] splitArray = dValue.split("\\.");

                            if(splitArray.length > 1) {
                                String dotValue = splitArray[1];
                                int diff = dotValue.length() + 1 - digLength;
                                if(diff > 0) {
                                    return source.subSequence(start,end - diff);
                                }
                            }
                        }
                    } else {// 无小数点
                        if(TextUtils.equals(".",source)) {// 输入小数点，不处理
                            return null;
                        }
                        if(dValue.length() > intLength - 1) {
                            return source.subSequence(0,0);
                        }
                    }
                    return null;
                }
            }

        };
        return lengthfilter;
    }


    /**
     * 判断系统中是否存在可以启动的相机应用
     *
     * @return 存在返回true，不存在返回false
     */
    public boolean hasCamera(Context mContext) {
        PackageManager packageManager = mContext.getPackageManager();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * 打印应用内存情况
     */
    public static void printMemory() {
        // 应用程序最大可用内存
        int maxMemory = ((int)Runtime.getRuntime().maxMemory())/1024/1024;
        // 应用程序已获得内存
        long totalMemory = ((int)Runtime.getRuntime().totalMemory())/1024/1024;
        // 应用程序已获得内存中未使用内存
        long freeMemory = ((int)Runtime.getRuntime().freeMemory())/1024/1024;

        Log.i("app","maxMemory=" + maxMemory + "M,totalMemory=" + totalMemory + "M,freeMemory=" + freeMemory + "M");
    }

    /**
     * 安装App程序
     *
     * @param mContext 上下文
     * @param appLocalPath App的本地地址
     */
    public static void installApp(Context mContext,String appLocalPath) {
        installApp(mContext,new File(appLocalPath));
    }

    /**
     * 安装App
     *
     * @param mContext 上下文
     * @param file 文件
     */
    public static void installApp(Context mContext,File file) {
        installApp(mContext,Uri.fromFile(file));
    }

    /**
     * 安装App
     *
     * @param mContext 上下文
     * @param uri App的本地地址
     */
    public static void installApp(Context mContext,Uri uri) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri,"application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    /**
     * 卸载App程序.
     *
     * @param mContext 上下文
     * @param packageName 包名
     */
    public static void uninstallApp(Context mContext,String packageName) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:" + packageName));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    /**
     * 根据包名获取意图
     *
     * @param mContext 上下文
     * @param packageName 包名
     * @return 意图
     */
    private static Intent getIntentByPackageName(Context mContext,String packageName) {
        return mContext.getPackageManager().getLaunchIntentForPackage(packageName);
    }

    /**
     * 启动指定包名的App
     *
     * @param mContext 上下文
     * @param packageName 包名
     * @return true: 打开成功<br>false: 打开失败
     */
    public static boolean startApp(Context mContext,String packageName) {
        Intent intent = getIntentByPackageName(mContext,packageName);
        if(intent != null) {
            mContext.startActivity(intent);
            return true;
        }
        return false;
    }

    /**
     * 根据包名判断App是否安装
     *
     * @param mContext 上下文
     * @param packageName 包名
     * @return true: 已安装<br>false: 未安装
     */
    public static boolean isInstallApp(Context mContext,String packageName) {
        return getIntentByPackageName(mContext,packageName) != null;
    }

    /**
     * 打开指定包名的App应用信息界面
     *
     * @param mContext 上下文
     * @param packageName 包名
     */
    public static void openAppInfo(Context mContext,String packageName) {
        Intent intent = new Intent();
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.parse("package:" + packageName));
        mContext.startActivity(intent);
    }

    /**
     * 可用来做App信息分享
     *
     * @param mContext 上下文
     * @param info 分享信息
     */
    public static void shareAppInfo(Context mContext,String info) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT,info);
        mContext.startActivity(intent);
    }

    /**
     * 获取App包信息版本
     */
    public static PackageInfo getPackageInfo(Context mContext) {
        PackageManager packageManager = mContext.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(mContext.getPackageName(),0);
        } catch(PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo;
    }

    /**
     * 获取设备ID
     */
    public static String getDeviceNumber(Context context) {
        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * 判断服务是否运行.
     *
     * @param context 上下文
     * @param className 判断的服务名字
     * @return true：服务正在在运行
     */
    public static boolean isServiceRunning(Context context,String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(100);
        if(serviceList.size() > 0) {
            for(int i = 0; i < serviceList.size(); i++) {
                if(serviceList.get(i).service.getClassName().equals(className)) {
                    isRunning = true;
                    break;
                }
            }
        }
        return isRunning;
    }

    /**
     * 判断当前App处于前台还是后台
     * <p>需要权限 <uses-permission android:name =“android.permission.GET_TASKS”/></p>
     * <p>并且必须是系统应用该方法才有效</p>
     *
     * @param context 上下文
     * @return true: 后台<br>false: 前台
     */
    public static boolean isAppBackground(Context context) {
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if(!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if(!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

}
